<?php
/**
 * Firebug
 *
 * @category	Log
 * @package		dayscript.log.adapter
 * @subpackage
 * @author		Juan Carlos Orrego <jcorrego@dayscript.com>
 * @copyright	2009 Dayscript Ltda.
 * @license
 * @version		1.0
 * @version		$Revision: 0 $
 * @filesource
 * @link		http://www.dayscript.com
 * @link		{docsLink}
 * @uses
 * @since		1.0
 * @modifiedby	$LastChangedBy: Juan Carlos Orrego $
 * @modified	$Date: 2009-10-27 $
 */

namespace dayscript\log\adapter;

/**
 * Firebug
 *
 * @category	Log
 * @package		dayscript.log.adapter
 * @subpackage
 * @author		Juan Carlos Orrego <jcorrego@dayscript.com>
 * @copyright	2009 Dayscript Ltda.
 * @license
 * @version		1.0
 * @link		http://www.dayscript.com
 * @link		{docsLink}
 * @uses		\dayscript\Map, \dayscript\log\Logger
 * @since		1.0
 * @modifiedby	$LastChangedBy: Nelson Daza $
 * @modified	$Date: 2010-04-16 $
 */
use dayscript;

class Firebug extends \dayscript\log\Logger	{
	/**
	 * Whether use html output.
	 * @var boolean
	 */
	protected $html = false;
	/**
	 * Firebug constructor
	 * @param string $name Firebug identificator
	 * @param array|\dayscript\Map $config File configuration
	 * @return Logger
	 */
	public function __construct( $name, \dayscript\Map $config )	{
		parent::__construct( $name, $config );
	}

	/**
	 * Firebug will only flush its log in a Web page that has already sent headers.
	 * @see \dayscript\log\Logger
	 */
	public function flush( )	{
		if( count( $this->buffer ) > 0 )	{
			
			if( $this->useBuffer )	{
				$this->html = ( $this->html || \dayscript\Enviroment::server( 'SERVER_NAME' ) != null );
				$this->useBuffer = ( !$this->html || ( $this->html && !\headers_sent( ) ) || \dayscript\log\LogManager::getType( ) != \dayscript\log\LogManager::TYPE_DIRECT );
			}
			
			if( !$this->useBuffer )	{
				echo "\n" . '<script language="javascript" type="text/javascript">';
				echo "\n" . '//<![CDATA[';
				echo "\n" . '//FireBug Log';
				foreach( $this->buffer as $msg )
					echo "\nconsole.log('" . \str_replace( array( "\\", "\n", "\r", "'", "\"" ), array( "\\\\", "\\n", "", "\\'", "\\\"" ), preg_replace( '/([\n\r\t ])+/', '$1', $msg ) ) . "' );";
				echo "\n" . '//]]>';
				echo "\n" . '</script>' . "\n";
				$this->buffer = array( );
			}
			
		}
	}

}